/* 初始化数据 */
import mongoose from "mongoose"
import colors from "colors"
import dotenv from 'dotenv'
import users from "./user.js"
import products from "./products.js"
import User from "../models/user.js"
import Product from "../models/product.js"
import Order from "../models/order.js"
import connectDB from "../config/db.js"

dotenv.config({ path: './.env.local' })
connectDB()

/* 插入数据 */
const importData = async () => {
  try {
    /* 清空 */
    await Order.deleteMany()
    await User.deleteMany()
    await Product.deleteMany()

    /* 数据插入 */
    const createUsers = await User.insertMany(users)
    /* 获取1个管理员 */
    const adminUserId = createUsers[0]._id
    const sampleProducts = products.map(item => ({
      ...item,
      userId: adminUserId
    }))
    await Product.insertMany(sampleProducts)
    console.log('数据插入成功'.green)
    process.exit()
  } catch (err) {
    console.log(`${err}`.red)
    process.exit(1)
  }
}

/* 销毁数据 */
const delData = async() => {
  try {
    /* 清空 */
    await Order.deleteMany()
    await User.deleteMany()
    await Product.deleteMany()
    console.log('数据删除成功'.green)
    process.exit()
  } catch (err) {
    console.error(`${err}`.red)
    process.exit(1)
  }
}

if(process.argv[process.argv.length-1] === '-d') {
  delData()
} else {
  importData()
}